//
//  HSWebVC.m
//  HolyShit
//
//  Created by Robin on 2017/3/24.
//  Copyright © 2017年 HolyShit. All rights reserved.
//

#import "HSWebVC.h"
#import <WebKit/WebKit.h>
#import "AppDelegate.h"

@interface HSWebVC ()<WKNavigationDelegate, WKUIDelegate>

@property (nonatomic, strong) WKWebView *wkview;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, assign) BOOL isNative;
@property (nonatomic, assign) BOOL isRoot;

@end

@implementation HSWebVC

- (void)dealloc
{
    if (_wkview) {
        if(!self.isNative){
            [_wkview removeObserver:self forKeyPath:@"canGoBack"];
        }
        [_wkview removeObserver:self forKeyPath:@"title"];
    }
}

- (instancetype)initWithUrl:(NSString *)url
{
    if (self = [super init]) {
        _url = url;
        _isNative = YES;
    }
    return self;
}

- (instancetype)init
{
    if (self = [super init]) {
        _url = [[NSUserDefaults standardUserDefaults] objectForKey:urlKey];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    self.wkview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    self.wkview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.wkview.allowsBackForwardNavigationGestures = YES;
    [self.wkview setNavigationDelegate:self];
    self.wkview.UIDelegate = self;
    [self.view addSubview:self.wkview];
    [self.wkview loadRequest:req];
    
    if(!self.isNative){
        [self.leftNavBtn setHidden:!self.wkview.canGoBack];
        [self.wkview addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    }
    [self.wkview addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    [self rightTitleWithIconText:@"" color:WHITE_COLOR];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    ((AppDelegate *)[UIApplication sharedApplication].delegate).allowRotate = YES;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    ((AppDelegate *)[UIApplication sharedApplication].delegate).allowRotate = NO;
}

- (void)leftButtonTouch {
    if ([self.wkview canGoBack]) {
        [self.wkview goBack];
    }
    else {
        [self my_pop:YES];
    }
}

- (void)rightButtonTouch
{
    if (self.wkview.backForwardList.backList.count < 1) {
        return;
    }
    [self.wkview goToBackForwardListItem:self.wkview.backForwardList.backList.firstObject];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"canGoBack"]) {
        [self.leftNavBtn setHidden:!self.wkview.canGoBack];
    }
    else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.wkview.title;
    }
    else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
    }
}

#pragma mark - wkdelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { // 类似UIWebView的 -webViewDidStartLoad:
    NSLog(@"didStartProvisionalNavigation");
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"didCommitNavigation");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // 类似 UIWebView 的 －webViewDidFinishLoad:
    NSLog(@"didFinishNavigation");
//    [self resetControl];
    if (webView.title.length > 0) {
        self.title = self.wkview.title;
    }
    
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    // 类似 UIWebView 的- webView:didFailLoadWithError:
    
    NSLog(@"didFailProvisionalNavigation");
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // 类似 UIWebView 的 -webView: shouldStartLoadWithRequest: navigationType:
    
    NSLog(@"4.%@",navigationAction.request);
    
    
    NSString *url = [navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    
    decisionHandler(WKNavigationActionPolicyAllow);
    
}
//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
//    
//}

#pragma mark - WKUIDelegate

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    // 接口的作用是打开新窗口委托
    [webView loadRequest:navigationAction.request];
    return nil;
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{    // js 里面的alert实现，如果不实现，网页的alert函数无效
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler();
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
    
}


- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    //  js 里面的alert实现，如果不实现，网页的alert函数无效  ,
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler(YES);
                                                      }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action){
                                                          completionHandler(NO);
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
    
    completionHandler(@"Client Not handler");
    
}


@end
